<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "menu".
 *
 * @property string $id 菜单id
 * @property string $name 菜单名
 * @property string $route 路由
 * @property string $icon 图标
 * @property int $pid 父菜单
 * @property string $extend
 */
class Menu extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'menu';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['pid'], 'integer'],
            [['name', 'route', 'icon'], 'string', 'max' => 255],
            [['extend'], 'string', 'max' => 1023],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => '菜单id',
            'name' => '菜单名',
            'route' => '路由',
            'icon' => '图标',
            'pid' => '父菜单',
            'extend' => 'Extend',
        ];
    }

    public static function Tree($pid = 0){
        $menus = self::find()
            // ->cache(1800)
            ->indexBy('id')
            ->asArray()
            ->all();

        $items = [];
        foreach($menus as $menu){
            $items[$menu['id']] = $menu;
        }
        //第二部 遍历数据 生成树状结构
        $tree = [];
        foreach($items as $key => $item){
            if(isset($items[$item['pid']])){
                $items[$item['pid']]['son'][] = &$items[$key];
            }else{
                $tree[] = &$items[$key];
            }
        }
        return $tree;
    }

    public static function SelectPid(){
        $menus = self::find()
            // ->cache(1800)
            ->indexBy('id')
            ->asArray()
            ->all();
        $select = [];
        foreach ($menus as $id => $item) {
            $select[$id] = Yii::t('menu', $item['name']);
        }
        return $select;
    }
}
